<template>
  <div class="news-management management-page">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="新闻名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入新闻名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="新闻来源">
          <el-select v-model="searchForm.source" placeholder="请选择新闻来源" clearable style="width: 150px">
            <el-option label="官方发布" :value="NewsSource.OFFICIAL" />
            <el-option label="媒体报道" :value="NewsSource.MEDIA" />
            <el-option label="其他来源" :value="NewsSource.OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新闻列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">新闻列表</span>
            <el-tag type="info" class="header-count" size="small">
              共 {{ total }} 条
            </el-tag>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>添加新闻
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedNews.length"
              @click="handleBatchDelete"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedNews.length ? `(${selectedNews.length})` : '' }}
            </el-button>
          </div>
        </div>
      </template>
      <el-table :data="newsList" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="新闻图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imgUrl"
              :preview-src-list="[row.imgUrl]"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 4px;"
              :initial-index="0"
              preview-teleported
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="新闻名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="summary" label="新闻简述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="time" label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="source" label="新闻来源" width="120">
          <template #default="{ row }">
            {{ getNewsSourceLabel(row.source) }}
          </template>
        </el-table-column>
        <el-table-column prop="browse" label="浏览量" width="100" align="center">
          <template #default="{ row }">
            <el-tooltip content="阅读量统计" placement="top">
              <span class="views-count">
                <el-icon><View /></el-icon>
                {{ row.browse || 0 }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="good" label="点赞量" width="100" align="center">
          <template #default="{ row }">
            <el-tooltip content="点赞数统计" placement="top">
              <span class="likes-count">
                <el-icon><Star /></el-icon>
                {{ row.good || 0 }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="新闻文件" min-width="150">
          <template #default="{ row }">
            <div v-if="row.url" class="file-info">
              <el-link 
                type="primary" 
                :href="row.url" 
                target="_blank"
                :underline="false"
              >
                <el-icon><Document /></el-icon>
                {{ getFileName(row.url) }}
              </el-link>
            </div>
            <span v-else>暂无文件</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑新闻对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加新闻' : '编辑新闻'"
      width="800px"
    >
      <el-form
        ref="newsFormRef"
        :model="newsForm"
        :rules="newsRules"
        label-width="100px"
      >
        <el-form-item label="新闻名称" prop="name">
          <el-input v-model="newsForm.name" placeholder="请输入新闻名称" />
        </el-form-item>

        <el-form-item label="新闻简述" prop="summary">
          <el-input
            v-model="newsForm.summary"
            type="textarea"
            rows="3"
            placeholder="请输入新闻简述"
          />
        </el-form-item>

        <el-form-item label="发布时间" prop="time">
          <el-date-picker
            v-model="newsForm.time"
            type="datetime"
            placeholder="选择发布时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="新闻来源" prop="source">
          <el-select v-model="newsForm.source" placeholder="请选择新闻来源" style="width: 100%">
            <el-option label="官方发布" :value="NewsSource.OFFICIAL" />
            <el-option label="媒体报道" :value="NewsSource.MEDIA" />
            <el-option label="其他来源" :value="NewsSource.OTHER" />
          </el-select>
        </el-form-item>

        <el-form-item label="新闻图片" prop="imageUrl">
          <el-upload
            class="news-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
          >
            <template #default>
              <el-button type="primary">选择图片</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="新闻文件" prop="fileUrl">
          <el-upload
            class="news-file-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <template #default>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持各种格式文件，且不超过50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadProps, UploadRawFile } from 'element-plus'
import { Plus, Download, Edit, Delete, View, Search, Refresh, Picture, Star, Document } from '@element-plus/icons-vue'
import { NewsSource, getNewsList, addNews, updateNews, deleteNews, batchDeleteNews, deleteNewsFile, uploadNewsImage, uploadNewsFile } from '@/api/news'
import type { News } from '@/api/news'

// 新增内容编辑器配置
interface NewsContent {
  id: number
  type: 'text' | 'image' | 'video'
  content: string
  description?: string
}

// 搜索表单
const searchForm = reactive({
  name: '',
  source: NewsSource.ALL
})

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const newsFormRef = ref<FormInstance>()
const submitting = ref(false)

const newsForm = ref({
  id: '',
  name: '',
  summary: '',
  time: '',
  source: NewsSource.OFFICIAL,
  imageUrl: '',
  fileUrl: '',
  fileName: '',
  fileSize: 0,
})

// 内容编辑相关
const contentDialogVisible = ref(false)
const currentContent = ref<NewsContent>({
  id: 0,
  type: 'text',
  content: '',
  description: ''
})
const isEditingContent = ref(false)

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')
const InputRef = ref<HTMLInputElement>()

// 表单校验规则
const newsRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入新闻名称', trigger: 'blur' }],
  summary: [{ required: true, message: '请输入新闻简述', trigger: 'blur' }],
  time: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
  source: [{ required: true, message: '请选择新闻来源', trigger: 'change' }],
  // imageUrl: [{ required: true, message: '请上传新闻图片', trigger: 'change' }],
  // fileUrl: [{ required: true, message: '请上传新闻文件', trigger: 'change' }]
})

// 列表数据
const loading = ref(false)
const newsList = ref<News[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedNews = ref<News[]>([])

// 获取新闻来源标签
const getNewsSourceLabel = (source: NewsSource) => {
  const labels = {
    [NewsSource.ALL]: '全部来源',
    [NewsSource.OFFICIAL]: '官方发布',
    [NewsSource.MEDIA]: '媒体报道',
    [NewsSource.OTHER]: '其他来源'
  }
  return labels[source]
}

// 获取新闻列表
const fetchNewsList = async () => {
  loading.value = true
  try {
    const response = await getNewsList({
      page: currentPage.value,
      size: pageSize.value,
      name: searchForm.name,
      source: searchForm.source
    })
    newsList.value = response.current_data
    total.value = response.total_record
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchNewsList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.source = NewsSource.ALL
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchNewsList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchNewsList()
}

// 文件上传处理
const handleImageChange = (file: any) => {
  newsForm.value.imageUrl = URL.createObjectURL(file.raw)
}

const handleImageRemove = () => {
  newsForm.value.imageUrl = ''
}

const handleFileChange = (file: any) => {
  newsForm.value.fileUrl = URL.createObjectURL(file.raw)
  newsForm.value.fileName = file.name
  newsForm.value.fileSize = file.raw.size
}

const handleFileRemove = () => {
  newsForm.value.fileUrl = ''
  newsForm.value.fileName = ''
  newsForm.value.fileSize = 0
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + ' MB'
  return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  Object.assign(newsForm.value, {
    id: '',
    name: '',
    summary: '',
    time: '',
    source: NewsSource.OFFICIAL,
    imageUrl: '',
    fileUrl: '',
    fileName: '',
    fileSize: 0,
    tags: [],
    content: []
  })
  dialogVisible.value = true
}

// 编辑新闻
const handleEdit = (row: News) => {
  dialogType.value = 'edit'
  newsForm.value = {
    id: row.id.toString(),
    name: row.name,
    summary: row.summary,
    source: row.source,
    time: row.time,
    imageUrl: row.imageUrl,
    fileUrl: row.url || '',
    fileName: '',
    fileSize: 0,
  }
  dialogVisible.value = true
}

// 删除新闻
const handleDelete = async (row: News) => {
  try {
    await ElMessageBox.confirm('确定要删除该新闻吗？', '提示', {
      type: 'warning'
    })
    await deleteNews(row.id.toString())
    ElMessage.success('删除成功')
    fetchNewsList()
  } catch (error) {
    console.error('删除新闻失败:', error)
  }
}

// 下载文件处理
const handleDownload = async (row: News) => {
  // try {
  //   loading.value = true
  //   const response = await downloadNewsFile(row.id)
  //   const blob = new Blob([response.data])
  //   const url = window.URL.createObjectURL(blob)
  //   const link = document.createElement('a')
  //   link.href = url
  //   link.download = row.url ? row.url.split('/').pop() || '新闻文件' : '新闻文件'
  //   document.body.appendChild(link)
  //   link.click()
  //   document.body.removeChild(link)
  //   window.URL.revokeObjectURL(url)
  //   ElMessage.success('文件下载成功')
  // } catch (error) {
  //   console.error('下载失败:', error)
  //   ElMessage.error('文件下载失败')
  // } finally {
  //   loading.value = false
  // }
}

// 打开内容编辑对话框
const openContentDialog = (item?: NewsContent) => {
  if (item) {
    currentContent.value = { ...item }
    isEditingContent.value = true
  } else {
    currentContent.value = {
      id: Date.now(),
      type: 'text',
      content: '',
      description: ''
    }
    isEditingContent.value = false
  }
  contentDialogVisible.value = true
}
// 文件上传配置
const uploadConfig = {
  accept: '.jpg,.jpeg,.png,.gif',
  beforeUpload: (file: UploadRawFile) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
      ElMessage.error('只能上传图片文件！')
      return false
    }
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      ElMessage.error('图片大小不能超过 5MB！')
      return false
    }
    return true
  }
} as UploadProps

// 更新提交处理
const handleSubmit = async () => {
  if (!newsFormRef.value) return
  
  await newsFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        submitting.value = true
        
        // 处理图片上传
        let imageUrl = newsForm.value.imageUrl
        if (imageUrl && imageUrl.startsWith('blob:')) {
          const imageInput = document.querySelector('.news-upload input[type="file"]') as HTMLInputElement
          const imageFile = imageInput?.files?.[0]
          if (imageFile) {
            try {
              const imageRes = await uploadNewsImage(imageFile)
              if (imageRes) {
                imageUrl = imageRes.toString()
              }
            } catch (error) {
              console.error('图片上传失败:', error)
              throw new Error('图片上传失败')
            }
          }
        }

        // 处理文件上传
        let fileUrl = newsForm.value.fileUrl
        if (fileUrl && fileUrl.startsWith('blob:')) {
          const fileInput = document.querySelector('.news-file-upload input[type="file"]') as HTMLInputElement
          const newsFile = fileInput?.files?.[0]
          if (newsFile) {
            try {
              const fileRes = await uploadNewsFile(newsFile)
              if (fileRes) {
                fileUrl = fileRes.toString()
              }
            } catch (error) {
              console.error('文件上传失败:', error)
              throw new Error('文件上传失败')
            }
          }
        }

        // 构建新闻数据
        const newsData = {
          id: newsForm.value.id,
          name: newsForm.value.name,
          summary: newsForm.value.summary,
          time: new Date(newsForm.value.time).toISOString(),
          source: newsForm.value.source,
          imgUrl: imageUrl || '',
          url: fileUrl || '',
          browse: 0,
          good: 0
        }

        if (dialogType.value === 'add') {
          await addNews(newsData)
          ElMessage.success('添加成功')
        } else {
          await updateNews(newsData.id, newsData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchNewsList()
      } catch (error) {
        console.error('提交失败:', error)
        if (error instanceof Error) {
          ElMessage.error(`提交失败: ${error.message}`)
        } else {
          ElMessage.error('提交失败')
        }
      } finally {
        submitting.value = false
      }
    } else {
      ElMessage.warning('请填写必填项')
    }
  })
}

const handleContentFileChange = (file: { raw: File }) => {
  if (file.raw) {
    currentContent.value.content = URL.createObjectURL(file.raw)
  }
}

// 表格选择处理
const handleSelectionChange = (selection: News[]) => {
  selectedNews.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedNews.value.length) {
    ElMessage.warning('请选择要删除的新闻')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的新闻吗？', '提示', {
      type: 'warning'
    })
    await batchDeleteNews(selectedNews.value.map(news => news.id.toString()))
    ElMessage.success('批量删除成功')
    fetchNewsList()
  } catch (error) {
    console.error('批量删除新闻失败:', error)
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 从URL中获取文件名
const getFileName = (url: string) => {
  if (!url) return ''
  const parts = url.split('/')
  return decodeURIComponent(parts[parts.length - 1])
}

onMounted(() => {
  fetchNewsList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss';

.news-management {
  .news-cover {
    width: 120px;
    height: 80px;
    border-radius: 4px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .cover-placeholder {
    width: 120px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
  }

  .news-upload {
    @extend .upload-container;
  }

  .editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-top: 10px;
  }
}

.views-count,
.likes-count {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  
  .el-icon {
    font-size: 16px;
  }
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .el-icon {
    margin-right: 4px;
  }
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  
  .el-icon {
    font-size: 24px;
  }
}
</style> 